package com.example.doufacedemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.doufacedemo.colordepth.GLPanel;
import com.example.doufacedemo.colordepth.SimpleViewer;
import com.hjimi.api.iminect.ImiDevice;
import com.hjimi.api.iminect.ImiDeviceAttribute;
import com.hjimi.api.iminect.ImiDeviceState;
import com.hjimi.api.iminect.ImiFrameMode;
import com.hjimi.api.iminect.ImiNect;

import org.bytedeco.javacpp.Pointer;
import org.bytedeco.xhfacelite.global.xhfacelite;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.example.doufacedemo.ActivityExtensionsKt.requestPermissionsEx;
import static com.example.doufacedemo.DouFacePayUtils.FECreate;
import static com.example.doufacedemo.DouFacePayUtils.FEdestory;
import static com.example.doufacedemo.DouFacePayUtils.FEload;
import static com.example.doufacedemo.DouFacePayUtils.dealBitmap;
import static com.example.doufacedemo.DouFacePayUtils.rgb2Bitmap;

public class DouActivity extends Activity {
    private Matrix matrix;
    private MainListener mainlistener;
    private ImiDevice mDevice;
    private static final int DEVICE_OPEN_SUCCESS = 0;
    private ImiDeviceAttribute mDeviceAttribute;
    private SimpleViewer mColorViewer;
    private GLPanel mGLColorPanel;
    //获取USB设备ACTION
    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    private UsbManager mUsbManager;
    private UsbDevice currentDevice;
    private BroadcastReceiver mUsbPermissionActionReceiver;
    private xhfacelite.XHF_SESS xhf_sess;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        //usb权限
        tryGetUsbPermission();
        initDou();
        //点击插入
        findViewById(R.id.btn_intert).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //插入到内存
                DouFacePayUtils.faceIntert(xhf_sess);
                //插入到本地
                DouFacePayUtils.faceSave(xhf_sess,MyApp.mContext);
            }
        });
        //打开摄像头
        findViewById(R.id.btn_open_carmer).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                new Thread(new OpenDeviceRunnable()).start();
            }
        });
        findViewById(R.id.btn_get_usb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tryGetUsbPermission();
            }
        });

    }



    private void initDou() {
        //3 第一次初始化算法，可以不用执行第3 的程序
        // 加载接口：xhfacelite.FELoad
        new Thread(new Runnable() {
            @Override
            public void run() {
                int xh_code = xhfacelite.XHFInit(
                        getExternalFilesDir("Face2").toString(),
                        "xhtest2020"
                );
                Log.i("main", "步骤1:初始化  = " + xh_code);
                xhf_sess = FECreate();
                FEload();
            }
        }).start();
    }

    private void init() {
        mGLColorPanel = findViewById(R.id.sv_attend_camera);
        matrix = new Matrix();
        float w = 0.8f;
        float y = 0.8f;
        matrix.postScale(w, y);
        matrix.postScale(-1f, 1f);

    }

    private class OpenDeviceRunnable implements Runnable {

        @Override
        public void run() {
            //get iminect instance.

            ImiNect.initialize();
            mDevice = ImiDevice.getInstance();
            mainlistener = new MainListener();

            mDevice.open(DouActivity.this, 0, mainlistener);

            mDevice.addDeviceStateListener(mainlistener);
        }
    }

    private class MainListener implements ImiDevice.OpenDeviceListener, ImiDevice.DeviceStateListener {

        @Override
        public void onOpenDeviceSuccess() {
            Log.i("main", "打开设备成功");
            MainHandler.sendEmptyMessage(DEVICE_OPEN_SUCCESS);
        }

        @Override
        public void onOpenDeviceFailed(String errorMsg) {
            //open device falied.
            Log.i("main", "打开设备失败");
        }

        @Override
        public void onDeviceStateChanged(String deviceInfo, ImiDeviceState state) {
            if (state == ImiDeviceState.IMI_DEVICE_STATE_CONNECT) {
                Toast.makeText(DouActivity.this, deviceInfo + " CONNECT", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(DouActivity.this, deviceInfo + " DISCONNECT", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void runViewer() {
        xhfacelite.XHF_SESS sess = new xhfacelite.XHF_SESS(new Pointer());
        mDeviceAttribute = mDevice.getAttribute();
        //mTVAttrs.setText("Device SerialNumber : " + mDeviceAttribute.getSerialNumber());
        boolean bPortrait = false;
        if (mDeviceAttribute != null && mDeviceAttribute.isPortraitDevice()) {
            bPortrait = true;
        }

        // set color frame mode
        ImiFrameMode colorFrameMode = mDevice.getCurrentFrameMode(ImiDevice.ImiStreamType.COLOR);
        mDevice.setFrameMode(ImiDevice.ImiStreamType.COLOR, colorFrameMode);
        Log.d("$$$$$$$$$", "color frame:" + colorFrameMode.getResolutionX() + ", " + colorFrameMode.getResolutionY());

        mColorViewer = new SimpleViewer(mDevice, ImiDevice.ImiStreamType.COLOR);
        mColorViewer.setGLPanel(mGLColorPanel);
        //回调处理帧图
        mColorViewer.setPreviewCallback(new SimpleViewer.PreviewCallback() {

            @Override
            public void onPreviewFrame(byte[] data, int width, int height) {
                Bitmap bitmap = rgb2Bitmap(data, width, height);
                int i = dealBitmap(bitmap, matrix, sess);
                if (i==0){
                    //关闭摄像头 回收资源
                    new Thread(new ExitRunnable()).start();
                }
            }
        });
        ViewGroup.LayoutParams colorParam = mGLColorPanel.getLayoutParams();
        colorParam.width = colorFrameMode.getResolutionX();
        colorParam.height = colorFrameMode.getResolutionY();
        if (bPortrait) {
            colorParam.width = 300;
            colorParam.height = 400;
        }
        mGLColorPanel.setLayoutParams(colorParam);

        mColorViewer.onStart();
        mDevice.startStream(ImiDevice.ImiStreamType.DEPTH.toNative() | ImiDevice.ImiStreamType.COLOR.toNative());
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭摄像头 回收资源
        new Thread(new ExitRunnable()).start();
        FEdestory(xhf_sess);
        unregisterReceiver(mUsbPermissionActionReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mColorViewer!=null){
            mColorViewer.onResume();
        }
    }

    private MyHandler MainHandler = new MyHandler(this);
    static class MyHandler extends Handler {
        WeakReference<DouActivity> mActivity;
        public MyHandler(DouActivity activity) {
            mActivity = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            DouActivity DouActivity = mActivity.get();
            switch (msg.what)
            {

                case DEVICE_OPEN_SUCCESS:
                    DouActivity.runViewer();
                    break;

            }
        }
    }

    private class ExitRunnable implements Runnable {

        @Override
        public void run() {
            if (mColorViewer != null) {
                mColorViewer.onPause();
            }
            //destroy color viewer.
            if (mColorViewer != null) {
                mColorViewer.onDestroy();
            }
            if(mDevice != null) {
                mDevice.close();
                mDevice = null;
                ImiDevice.destroy();
            }
            ImiNect.destroy();

        }
    }








    //获取USB权限
    private void tryGetUsbPermission(){



        mUsbPermissionActionReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    context.unregisterReceiver(this);//解注册
                    synchronized (this) {
                        UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if(null != usbDevice){
                                Log.e("TAG",usbDevice.getDeviceName()+"已获取USB权限");
                            }
                        }
                        else {
                            //user choose NO for your previously popup window asking for grant perssion for this usb device
                            Log.e("TAG",String.valueOf("USB权限已被拒绝，Permission denied for device" + usbDevice));
                        }
                    }

                }
            }
        };



        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);

        if(mUsbPermissionActionReceiver != null) {
            registerReceiver(mUsbPermissionActionReceiver, filter);
        }

        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

        boolean has_idcard_usb = false;
        for (final UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {

            if(usbDevice.getVendorId() == 11707 && usbDevice.getProductId() == 518)//身份证设备USB
            {
                has_idcard_usb = true;
                Log.e("TAG",usbDevice.getDeviceName()+"已找到身份证USB");
                if(mUsbManager.hasPermission(usbDevice)){
                    Log.e("TAG",usbDevice.getDeviceName()+"已获取过USB权限");
                }else{
                    Log.e("TAG",usbDevice.getDeviceName()+"请求获取USB权限");
                    mUsbManager.requestPermission(usbDevice, mPermissionIntent);
                }
            }

        }

        if(!has_idcard_usb)
        {
            Log.e("TAG","未找到身份证USB");
        }

    }


}
